#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

from heat.common import exception
from heat.engine import clients
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.neutron import neutron

from heat.engine.resources.qingresources import qing_utils
from heat.engine.resources.qingresources import qing_cfg

class VPC(resource.Resource):
    PROPERTIES = (
        ROUTER, EIP,
    ) = (
        'Router', 'Eip',
    )

    properties_schema = {
        ROUTER: properties.Schema(
            properties.Schema.STRING,
            _('Router id for the vpc'),
        ),
        EIP: properties.Schema(
            properties.Schema.STRING,
            _('EIP for the vpc')
        ),
    }

    attributes_schema = {
        'AllocationId': _('ID that Qing assigns to represent the allocation of'
                          ' the address for use with Qingcloud VPC. Returned only'
                          ' for VPC elastic IP addresses.'),
        'IPAddrress': _('IP address of the eip')
    }

    def handle_create(self):
        iaas = qing_utils.CloudIaas()
        # The VPC's net and router are associated by having identical names.
        net_props = {'name': self.physical_resource_name()}
        router_props = {'name': self.physical_resource_name()}

        #net = client.create_network({'network': net_props})['network']
        #client.create_router({'router': router_props})['router']
        print(router_props['name'])
        rets = iaas.create_routers(router_props['name'])
        if rets[0] != 0:
            raise exception.error(_("create vpc router faild")%router_props['name'])

        #TBD:
        #another work should be done:
        # get eip address and associated it 
        #

        '''
        in qingcloud, the network id is router id
        '''
        self.resource_id_set(rets[1][0])

    @staticmethod
    def network_for_vpc(client, network_id):
        return network_id

    @staticmethod
    def router_for_vpc(client, network_id):
        '''
        in qingcloud, only 1 router for vpc, the router and vpc is the same
        '''
        return network_id
        '''
        # first get the neutron net
        net = VPC.network_for_vpc(client, network_id)
        # then find a router with the same name
        routers = client.list_routers(name=net['name'])['routers']
        if len(routers) == 0:
            # There may be no router if the net was created manually
            # instead of in another stack.
            return None
        if len(routers) > 1:
            raise exception.Error(
                _('Multiple routers found with name %s') % net['name'])
        return routers[0]
        '''

    def check_create_complete(self, *args):
        return True
        '''
        net = self.network_for_vpc(self.neutron(), self.resource_id)
        if not neutron.NeutronResource.is_built(net):
            return False
        router = self.router_for_vpc(self.neutron(), self.resource_id)
        return neutron.NeutronResource.is_built(router)
        '''

    def handle_delete(self):
        iaas = qing_utils.CloudIaas()
        print("-----------------------------------")
        print(self.resource_id)        
        rets = iaas.delete_routers(self.resource_id)
        if rets[0] != 0:
            raise exception.Error(_('delete vpc router failed %s')% self.resource_id)
        
        return
        '''
        from neutronclient.common.exceptions import NeutronClientException
        client = self.neutron()
        router = self.router_for_vpc(client, self.resource_id)
        try:
            client.delete_router(router['id'])
        except NeutronClientException as ex:
            if ex.status_code != 404:
                raise ex

        try:
            client.delete_network(self.resource_id)
        except NeutronClientException as ex:
            if ex.status_code != 404:
                raise ex
        '''


def resource_mapping():
    return {
        'Heat::Qing::VPC': VPC,
    }
